
// react
import React, { useEffect, useState } from "react";
// lib
import { Modal, Form, InputNumber, Col, Row, DatePicker, Select } from "antd";
// components & widget
// style
// config
import { MODULE_NAME } from "./config";
import { MODAL_STYLE } from "project/config";
import { INPUT_REQUIRED_RULE } from "project/validRules";
// script & methods & public
// store
import { observer } from "mobx-react";
import { state } from "./state";
// import { addBook, getShelfByName } from "./controller";
import timeUtils from "utils/timeUtils";
import { addCopy, getBookByTitleOrIsbn, updateCopy } from "./controller";
import dayjs from "dayjs";
// controller
// import { addMenu, updateMenu } from "./controller";
// interface
// 其它

function EditModal() {
  // 书架列表
  const [shelfLevels, setShelfLevels] = useState<number[]>([]);
  // 书名搜索项
  const [bookSearch, setBookSearch] = useState<string>();
  // 搜索后的结果列表
  const [bookList, setBookList] = useState<BookDto[]>([]);
  const [form] = Form.useForm();
  const show = state.editModalShow;
  const title = `${MODULE_NAME}`;

  useEffect(() => {
    if (show) {
      form.resetFields();
    }// 编辑时回显数据
    if (state.editInfo) {
      const info = state.editInfo;
      setBookList([{bookId:info.bookId,title:info.title||"" ,author:info.author || "",publisher:info.publisher,isbn:info.isbn||""}])
      form.setFieldsValue({
        ...info,
        buyDate:dayjs(info.buyDate,'YYYY-MM-DD')
      });
    }
  }, [form, show]);
  //当选定书架时，生成书架层数列表
  const onChange = (name: number) => {
    const maxL = state.getShelfList().find(item => item.shelfId === name)?.maxLevel
    if (maxL && maxL > 0) {
      const numbers = new Array()
      for (let index = 0; index < maxL; index++) {
        numbers[index] = index + 1
      }
      setShelfLevels(numbers)
    }
  }
  // 关闭窗口
  const handleCancel = () => {
    state.editModal = false;
  };
  // 图书搜索内容防抖
  useEffect(() => {
    const getData = setTimeout(() => {
      if (!bookSearch) return
      getBookByTitleOrIsbn(bookSearch, setBookList)
    }, 1000)
    return () => clearTimeout(getData)
  }, [bookSearch])
  // 提交新增数据
  const handleOk = async () => {
    try {
      const result = await form.validateFields();
      if (result.buyDate) { // 格式化日期
        result.buyDate = timeUtils.format(result.buyDates)
      }
      if (state.editInfo) { // 编辑时附带副本id
        updateCopy(result,state.editInfo.copyId)
      } else {// 新增副本
        addCopy(result)
      }
    } catch (error) {
      //
    }
  };
  return (
    <Modal
      title={title}
      open={show}
      onCancel={handleCancel}
      onOk={handleOk}
      width={MODAL_STYLE.COL2}
      destroyOnClose
      maskClosable
      forceRender
      okButtonProps={{
        loading: state.editModalLoading,
      }}
    >
      <Form {...MODAL_STYLE.FORM_6_18} form={form}>
        {/* <Row gutter={MODAL_STYLE.FORM_ROW_GUTTER}> */}
        <Col span={24}>
          <Form.Item labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} name="bookId" label="关联图书" rules={[INPUT_REQUIRED_RULE]}>
            <Select filterOption={false} placeholder={"请输入书名搜索"} allowClear showSearch onSearch={(e) => setBookSearch(e)}>
              {bookList.map(item => (
                <Select.Option key={item.bookId} value={item.bookId}>
                  {item.title}-{item.author}-{item.isbn}-{item.publisher}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
        <Row>
          <Col span={12}>
            <Form.Item name="sourceId" label="图书来源" rules={[INPUT_REQUIRED_RULE,]}>
              <Select >
                {state.getSourceList().map(item => (
                  <Select.Option key={item.sourceId} value={item.sourceId}>
                    {item.sourceName}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name="buyDate" label="入库日期" rules={[INPUT_REQUIRED_RULE]}>
              <DatePicker />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item name="buyPrice" label="买入价格(元)" rules={[INPUT_REQUIRED_RULE]}>
              <InputNumber min={0.01} precision={2} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name="shelfId" label="所在书架" shouldUpdate rules={[INPUT_REQUIRED_RULE,]}>
              <Select allowClear showSearch placeholder="请选择书架" optionFilterProp="label" onChange={onChange} >
                {state.getShelfList().map(item => (
                  <Select.Option key={item.shelfId} value={item.shelfId} label={item.shelfName}>
                    {item.shelfName}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item name="shelfLevel" label="层数" rules={[INPUT_REQUIRED_RULE,]}>
              <Select onChange={onChange}>
                {shelfLevels.map(item => (
                  <Select.Option key={item} value={item}>
                    第{item}层
                  </Select.Option>
                ))}
              </Select>

            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
}

export default observer(EditModal);
